import axios from "axios";
import router from "@/router/index.js";
import {progress} from "@/utils/progress.js";
import {netConfig} from '@/config/net.config';
import {useUserStore} from "@/store/index.js";

const {baseURL, contentType, requestTimeout, withCredentials} = netConfig;
import {message, notification} from "ant-design-vue";

const request = axios.create({
    baseURL: baseURL,
    timeout: requestTimeout,
    withCredentials: withCredentials,
    headers: {
        'Content-Type': contentType,
    },
});

// 请求拦截器
request.interceptors.request.use(config => {
    progress().start(); // 进度条开始
    const token = localStorage.getItem("token");
    if (token) {
        config.headers["Access-Token"] = "Bearer " + token;
        config.headers["Authorization"] = "Bearer " + token;
    }
    // 请求时缓存该请求，路由跳转时取消, 如果timeout值过大，可能在上一个次请求还没完成时，切换了页面。
    // config.cancelToken = new axios.CancelToken(async cancel => {
    // await store.dispatch("app/execCancelToken", {cancelToken: cancel});
    // });
    return config;
}, error => {
    progress().done(); // 进度条结束
    return Promise.reject(error);
});

// 响应拦截器
request.interceptors.response.use(async response => {
    const useStore = useUserStore();
    if (response.data.code === 401) {
        useStore.accountLogout().then(res => {
            if (res) {
                router.push("/login");
            }
        });
    }
    progress().done(); // 进度条结束
    return response.data;
}, error => {
    // const useStore = useUserStore();
    progress().done(); // 进度条结束
    if (error.response) {

    } else {
        let msg = null;
        let {message} = error;
        if (message === "Network Error") {
            msg = "连接异常";
        }
        if (message.includes("timeout")) {
            msg = "请求超时";
        }
        if (message.includes("Request failed with status code")) {
            const code = message.substr(message.length - 3);
            msg = "接口" + code + "异常";
        }
        message.error(msg);
    }
    return Promise.reject(error);
    // if (error.response) {
    //     const data = error.response.data;
    //     if (error.response.status === 403) {
    //         notification.error({
    //             message: "无权限访问",
    //             description: data.message,
    //         });
    //     }
});

export default request;